<template>
  <div class="container">
    <div class="header">
      {{ group.groupName }}
      <div class="option">
        <el-dropdown
          trigger="click"
          placement="bottom-start"
          @command="handleOption"
        >
          <el-button size="mini" plain trigger="click" type="info">
            <i class="el-icon-s-tools"></i> 操作
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="edit">修改信息</el-dropdown-item>
            <el-dropdown-item command="add">新增小组</el-dropdown-item>
            <el-dropdown-item
              command="remove"
              :disabled="group.groupId == 10000"
            >
              删除该组</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <!-- 基本信息 -->
    <div class="content">
      <div class="detail">
        <img :src="prefixPicUrl + group.image + '?r=' + Math.random()" alt="" />
        <div class="word">
          {{ group.groupDetail }}
        </div>
      </div>
      <hr />
      <div class="baseinfo">
        <div v-if="group.teacher != null" class="row">
          <i class="el-icon-s-custom"></i
          ><label> 指导教师：{{ group.teacher }}老师</label
          ><i class="el-icon-phone"></i
          ><label> 电话：{{ group.teacherMobile }}</label>
        </div>
        <div v-for="leader in group.leaders" :key="leader.userId" class="row">
          <i class="el-icon-user-solid"></i
          ><label> 负 责 人： {{ leader.realName }}</label
          ><i class="el-icon-s-order"></i
          ><label> 学号：{{ leader.studentId }}</label
          ><i class="el-icon-phone"></i><label> 电话：{{ leader.mobile }}</label
          ><i class="el-icon-chat-dot-round"></i
          ><label> QQ：{{ leader.qq }}</label>
        </div>
      </div>
      <!-- {{ group.groupDetail }} -->
    </div>

    <!-- 上传的Dialog -->
    <el-dialog
      :visible.sync="showUploadDialog"
      :title="'在 ' + group.groupName + ' 下添加小组'"
      width="50%"
      :modal-append-to-body="false"
    >
      <el-form
        ref="groupForm"
        :model="groupForm"
        label-width="80px"
        :rules="groupFormRules"
      >
        <el-form-item label="组名" prop="groupName">
          <el-input
            v-model="groupForm.groupName"
            placeholder="请输入新增组名"
          ></el-input>
        </el-form-item>
        <el-form-item label="小组简介" prop="groupDetail">
          <el-input
            v-model="groupForm.groupDetail"
            placeholder="请输入小组介绍"
            autosize
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>
        <div class="submitForm">
          <el-button type="info" plain @click="cancelGroupForm">取消</el-button>
          <el-button
            type="primary"
            plain
            @click="submitUploadGroupForm('groupForm')"
            >提交</el-button
          >
        </div>
      </el-form>
    </el-dialog>

    <!-- 修改的Dialog -->
    <el-dialog
      :visible.sync="showEditDialog"
      title="修改小组信息"
      width="50%"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <el-form ref="groupForm" :model="groupForm" label-width="85px">
        <el-form-item label="组名" prop="groupName">
          <el-input v-model="groupForm.groupName" placeholder="请输入新组名">
          </el-input>
        </el-form-item>
        <el-form-item label="指导教师" prop="instructor">
          <el-select
            v-model="groupForm.instructor"
            filterable
            placeholder="请选择新任指导老师（可搜索）"
          >
            <el-option
              v-for="item in teaList"
              :key="item.teacherId"
              :value="item.teacherId"
              :label="item.teacherName"
            >
              <span style="float: left">{{ item.teacherName }}</span>
              <span style="float: right; color: #8492a6; font-size: 80%">{{
                item.teacherId
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组长" prop="groupLeader">
          <el-select
            v-model="groupForm.leaderId"
            filterable
            remote
            multiple
            :remote-method="getRemoteGroupLeader"
            :loading="remoteLoading"
            placeholder="请指定新任组长（可搜索）"
            @change="changeHandler"
          >
            <el-option
              v-for="item in leaderOptions"
              :key="item.userId"
              :value="item.userId"
              :label="item.realName"
            >
              <span style="float: left">{{ item.realName }}</span>
              <span style="float: right; color: #8492a6; font-size: 80%">{{
                item.studentId
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小组简介" prop="groupDetail">
          <el-input
            v-model="groupForm.groupDetail"
            placeholder="请输入新小组介绍"
            autosize
            type="textarea"
            rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="小组LOGO" prop="img">
          <el-upload
            ref="upload_attach"
            action="abc"
            accept="image/*"
            :limit="1"
            :file-list="fileList"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-exceed="handleFileExceed"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <div class="submitForm">
          <el-button type="info" plain @click="cancelGroupForm">取消</el-button>
          <el-button
            type="primary"
            plain
            @click="submitEditGroupForm('groupForm')"
            >提交</el-button
          >
        </div>
      </el-form>
    </el-dialog>
    <cropper
      v-if="showCropper"
      :dialog-visible="showCropper"
      :cropper-img="cropperImg"
      @update-cropper="updateCropper"
      @colse-dialog="closeDialog"
      @upload-img="uploadImg"
    />
  </div>
</template>

<script>
import loading from "../../loading.js";
import Config from "../config.js";
import Cropper from "../utils/cropper.vue";
import CompressImg from "../utils/compressImg.js";
export default {
  components: {
    Cropper,
  },
  props: {},

  data() {
    return {
      group: {},
      file: "",
      fileList: [],
      blobImg: "",
      cropperImg: "", // 需要裁剪的图片
      showCropper: false, // 是否显示裁剪框
      showEditDialog: false,
      showUploadDialog: false,
      selectGroupId: "",
      remoteLoading: false,
      groupTypeOptions: [],
      leaderOptions: [],
      teaList: [],
      groupForm: {
        leaderId: "",
        groupName: "",
        groupDetail: "",
        instructor: "",
      },
      prefixPicUrl: "",
      uploadUrl: `${this.HOST}/admin/api/uploadUserModel`,
      token: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      groupFormRules: {
        groupName: [
          { required: true, message: "请输入新建组名", trigger: "blur" },
        ],
        groupDetail: [
          { required: true, message: "请输入小组简介", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    this.getLevelGroupList();
    this.getTeacherList();
    this.prefixPicUrl = Config.picPrefixUrl;
  },

  methods: {
    changeHandler() {
      // console.log("leaderIds",this.groupForm.leaderId);
      // console.log(this.groupForm.importable);
    },
    updateGroupId(groupId) {
      console.log("groupId1", groupId);
      this.getGroupById(groupId);
    },
    /**
     * 处理点击 更多操作
     */
    handleOption(command) {
      if (command == "edit") {
        this.editGroup();
      } else if (command == "add") {
        this.addGroup();
      } else if (command == "remove") {
        this.removeGroup(this.group.groupId);
      }
    },
    async getLevelGroupList() {
      const res = await this.$axios.get(`${this.HOST}/group/api/childNode`);
      // const res = await this.$axios.get(`${this.HOST}/group/api/groupTree`);
      if (res.data.meta.code == 200) {
        let arr = [];
        arr.push(res.data.data.group);
        this.groupTypeOptions = arr;
        this.selectGroupId = arr[0].groupId;
        console.log("组别获取成功！", this.groupTypeOptions);
        // console.log(this.queryInfo.groupId);
      } else if (res.status != 200) {
        this.$message({
          message: "获取失败！",
          type: "error",
        });
      }
    },
    /**
     * 根据小组id获取组信息，初始加载的时候就触发
     */
    async getGroupById(groupId) {
      //   console.log("groupId", groupId);
      const res = await this.$axios.get(
        `${this.HOST}/group/api/singleGroup/` + groupId
      );
      //   console.log("group", res);
      if (res.data.meta.code == 200) {
        this.group = res.data.data.group;
        console.log("小组信息获取成功！", this.group);
        // console.log(this.queryInfo.groupId);
      }
    },
    async getTeacherList() {
      if (window.sessionStorage.getItem("teaList") != null) {
        this.teaList = JSON.parse(window.sessionStorage.getItem("teaList"));
        console.log("已从本地取得TeaList！");
        return;
      }
      const res = await this.$axios.get(`${this.HOST}/teacher/api/teacher`);
      // console.log("teaRes", res);
      if (res.data.meta.code == 200) {
        this.teaList = res.data.data.teachers;
        window.sessionStorage.setItem("teaList", JSON.stringify(this.teaList));
        console.log("获取教师列表成功！", this.teaList);
      }
    },
    // handleLeaderSelect(item) {
    //   console.log("item", item);
    //   this.groupForm.leaderName = item.realName;
    //   this.groupForm.leaderId = item.userId;
    // },
    // handleChange(){
    //     console.log(this.group.leaderId);
    // },
    getRemoteGroupLeader(query) {
      let _this = this;
      //   console.log("innnnn", query);
      setTimeout(async () => {
        if (query == "" || typeof query == "undefined") return;
        console.log("word", query);
        _this.remoteLoading = true;
        const res = await this.$axios.get(
          `${this.HOST}/group/api/queryMember/` + query
        );
        console.log("res", res);
        _this.leaderOptions = res.data.data.result;
        _this.remoteLoading = false;
      }, 1000);
    },
    editGroup() {
      // console.log("edit", this.activeGroup);
      this.showEditDialog = true;
      this.groupForm = this.group;
      this.getGroupById(this.group.groupId);
    },
    addGroup() {
      // console.log("app", this.activeGroup);
      this.groupForm = {};
      this.showUploadDialog = true;
    },
    async submitEditGroupForm() {
      let params = {
        groupId: this.group.groupId,
        groupName: this.groupForm.groupName,
        groupDetail: this.groupForm.groupDetail,
      };
      if (typeof this.groupForm.instructor != "undefined") {
        params.teacherId = this.groupForm.instructor;
      }
      if (this.groupForm.leaderId != null && this.groupForm.leaderId != "") {
        // console.log("type",(typeof this.groupForm.groupLeader));
        params.leaderIds = this.groupForm.leaderId;
      }
      //   console.log("params", params);
      let formData = new FormData();
      Object.keys(params).forEach((key) => {
        formData.append(key, params[key]);
      });
      formData.append("file", this.blobImg);
      const _loading = loading(`上传中，请稍等...`);
      this.showEditDialog = false;
      const config = {
        onUploadProgress: (progressEvent) => {
          this.progressPercent = Number(
            ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0)
          );
          _loading.setText("上传中，进度：" + this.progressPercent + "%"); //更新dialog进度，优化体验
          // console.log(this.progressPercent);
        },
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      try {
        const res = await this.$axios.post(
          `${this.HOST}/group/api/updateGroup`,
          formData,
          config
        );
        if (res.data.meta.code == 200) {
          this.$message({
            message: "修改成功！",
            type: "success",
            showClose: true,
          });
          window.sessionStorage.removeItem("groupTree");
          this.getGroupById(this.group.groupId);
          // this.getLevelGroupList();
                  this.$router.go(0);

        }
      } finally {
        _loading.close();
      }
    },
    async submitUploadGroupForm(formName) {
      let isValid = true;
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          isValid = false;
          return;
        }
      });
      if (!isValid) return;
      this.showUploadDialog = false;
      let params = {
        parentId: this.group.groupId,
        groupName: this.groupForm.groupName,
        groupDetail: this.groupForm.groupDetail,
      };
      console.log("params", params);
      const res = await this.$axios.post(
        `${this.HOST}/group/api/addGroup`,
        params
      );
      if (res.data.meta.code == 200) {
        this.$message({
          message: "新增成功！",
          type: "success",
          showClose: true,
        });
        window.sessionStorage.removeItem("groupTree");
        this.$router.go(0);
      }
    },
    cancelGroupForm() {
      this.groupForm = {};
      this.showUploadDialog = false;
      this.showEditDialog = false;
    },
    removeGroup(id) {
      this.$confirm("此操作将永久删除该组, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          console.log("deleteid=", id);
          const res = await this.$axios.get(
            `${this.HOST}/group/api/deleteGroup/${id}`
          );
          if (res.data.meta.code == 200) {
            this.$message({
              message: "删除成功",
              type: "error",
            });
            window.sessionStorage.removeItem("groupTree");
            this.$router.push("/structure");
          }
        })
        .catch(() => {});
    },
    handleFileChange(file) {
      const { raw } = file;
      this.openCropper(raw);
    },
    handleFileExceed() {
      this.$message.warning("只能上传一张图片哦！");
    },
    openCropper(file) {
      var files = file;
      let isLt2M = files.size > 2 << 20;
      if (isLt2M) {
        this.$message.error("请上传2M内的图片");
        return false;
      }
      var reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.cropperImg = data;
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(files);
      this.showCropper = true;
    },
    // 上传图片
    async uploadImg(file) {
      // console.log("bef file", file);
      let img = await CompressImg(file);
      console.log("imgUrl", img);
      this.blobImg = img.file;
      this.showCropper = false;
    },
    updateCropper() {
      this.$refs.fileUpload.$children[0].$el.click();
    },
    // 关闭窗口
    closeDialog() {
      this.fileList.pop();
      this.showCropper = false;
    },
  },
};
</script>

<style lang="less" scoped>
.header {
  color: white;
  font-size: 28px;
  font-weight: bold;
  width: 100%;
  text-align: center;
  height: 50px;
  margin-bottom: 10px;
}

.content {
  width: 75%;
  min-width: 800px;
  margin: auto;
  border-radius: 5px;
  padding: 20px;
  background-color: white;
  padding-right: 40px;
  font-weight: normal;
  padding-left: 40px;
  color: gray;
  margin-bottom: 20px;

  .detail {
    text-indent: 28px;
    color: rgb(83, 83, 83);
    display: flex;

    img {
      width: 150px;
      max-height: 100px;
      height: 100%;
      margin-right: 10px;
    }

    .word {
      padding-top: 5px;
      font-size: 14px;
    }
  }

  .baseinfo {
    font-size: 14px;

    .row {
      label {
        display: inline-block;
        width: 160px;
      }
    }
  }
}

.option :hover {
  cursor: pointer;
}

.option {
  position: absolute;
  font-size: 22px;
  top: 95px;
  right: 11%;
}

.submitForm {
  display: flex;
  justify-content: center;
}
.groupLeader {
  li {
    line-height: normal;
    padding: 7px;
    display: flex;

    .info {
      display: flex;
      justify-content: space-between;

      .name {
        font-size: 14px;
        display: inline-block;
      }

      .id {
        display: inline-block;
        font-size: 8px;
        color: gray;
        font-size: 80%;
      }
    }
  }
}
</style>
